let express = require("express");
let api = express.Router();
let tokenManager = require("../classes/token.js");

//refresh token
api.get("/freshToken", function(req , res , next){
    let oldToken = req.headers.token;
    
    // 解码token
    let userID = tokenManager.decodeToken( oldToken ).user_id;
    console.log("userID: ", !userID);
    if( !userID  ){
        next({
            status: 400,
            code: 400013,
            msg: "用户身份不存在"
        })
        return ;
    }
    let newToken = tokenManager.generateToken({user_id : userID});
    res.statusCode = 200;
    res.send(JSON.stringify({
        code: 0,
        data: {
            token: newToken
        }
    }));
    res.end();
});

//错误处理
api.use(function( err , req , res , next){
    // console.log("err: ", err);
    if( err ){

        res.statusCode= err.status;
        res.send( JSON.stringify({
            code: err.code,
            msg: err.msg
        }) );
        res.end();
        
    }else{
        next();
    }
    
});

module.exports = api;